/**
 * 制作：
 * b站ID：快乐的狼王
 * Cocos论坛：https://forum.cocos.org/t/scrollview/94132
 * 联系方式：QQ群：Cocos3D研究院-伊风
 */

import { ItemPanelController } from "./ItemPanelController";

const { ccclass, property } = cc._decorator;

enum ViewType {
    '横屏' = 1,
    '竖屏' = 2,
}

enum CountentType {
    '横屏：左到右；竖屏：上到下' = 1,
    '横屏：右到左；竖屏：下到上' = 2,
}

@ccclass
export default class ScrollViewManager extends cc.Component {

    private __Scrollview: cc.ScrollView;

    @property({
        tooltip: '每行或每列的个数'
    })
    Division = 1;

    @property({
        tooltip: '是否选择自动获取最佳面板数量'
    })
    IfAutoGetMaxPanel = true;

    @property({
        type: cc.Node,
        displayName: '填充面板',
        tooltip: '需要填充进组件的面板'
    })
    private Panel_Index: cc.Node = null;

    @property({
        tooltip: '上方留空的大小',
        displayName: '上方留空_TOP',
        visible() {
            return this.ViewType == 2;
        }
    })
    private CutTop = 10;

    @property({
        tooltip: '下方留空的大小',
        displayName: '下方留空_BOTTOM',
        visible() {
            return this.ViewType == 2;
        }
    })
    private CutBottom = 10;

    @property({
        tooltip: '左方留空的大小',
        displayName: '左方留空_LEFT',
        visible() {
            return this.ViewType == 1;
        }
    })
    private CutLeft = 10;

    @property({
        tooltip: '右方留空的大小',
        displayName: '右方留空_RIGHT',
        visible() {
            return this.ViewType == 1;
        }
    })
    private CutRight = 10;

    /** x轴间隔 */
    @property({
        tooltip: '面板之间，x轴方向的间隙',
        displayName: '面板左右间距_X',
        visible() {
            if (this.ViewType == 1 || (this.ViewType == 2 && this.Division > 1)) {
                return true;
            }
            else {
                return false;
            }
        }
    })
    private Interval_X = 10;

    /** y轴间隔 */
    @property({
        tooltip: '面板之间，y轴方向的间隙',
        displayName: '面板上下间距_Y',
        visible() {
            if (this.ViewType == 2 || (this.ViewType == 1 && this.Division > 1)) {
                return true;
            }
            else {
                return false;
            }
        }
    })
    private Interval_Y = 10;

    /** 面板数量 */
    @property({
        tooltip: '展示的面板最大数量，可以手动设置，可以自动设置',
        displayName: '最大面板数量_MAXCOUNT',
        visible() {
            return this.IfAutoGetMaxPanel == false;
        }
    })
    private MaxPanel = 10;


    /** 1横屏，2竖屏，3未定义 */
    @property({
        type: cc.Enum(ViewType),
        tooltip: '横屏排列，竖屏排列'
    })
    private ViewType = ViewType.横屏;

    /** 1左到右，上到下，2右到左，下到上，3未定义 */
    @property({
        type: cc.Enum(CountentType),
        tooltip: '1左到右，上到下，2右到左，下到上，3未定义'
    })
    private CountentType = CountentType["横屏：左到右；竖屏：上到下"];

    @property({
        displayName: '是否启用文字节点',
    })
    IsLabelPanel = false

    @property({
        type: cc.Node,
        displayName: '文字父节点',
        tooltip: '存放文字面板的父节点',
        visible() {
            return this.IsLabelPanel == true;
        }
    })
    private LabelContent: cc.Node[] = [];

    @property({
        type: cc.Node,
        displayName: '填充面板_文字',
        tooltip: '需要填充进组件的面板_文字',
        visible() {
            return this.IsLabelPanel == true;
        }
    })
    private LabelPanel_Index: cc.Node[] = [];

    @property({
        displayName: '滑动系数',
        tooltip: '滑动系数，0-1。',
        min: 0,
        max: 1,
        step: 0.1,
        slide: true,
        visible() {
            return this.IsBrake == true;
        }
    })
    Brake: number = 1;

    @property({
        displayName: '是否开启滑动',
        tooltip: '是否开启滑动',
    })
    IsBrake = false;

    private MaskPanel: cc.Node;
    private CountentPanel: cc.Node = null;

    PanelCount = 0;

    private Panel_IndexSize = [];
    private PanelController = null;

    private _IsLoad = false;
    private _PanelLoad = false;



    onLoad() {
        if (cc.find('pub', this.node)) {
            cc.find('pub', this.node).active = false;
        }
    }

    onStart() {
        this.__Scrollview = this.node.getComponent(cc.ScrollView);
        this.MaskPanel = cc.find('view', this.node);
        if (this.CountentPanel == null) {
            this.CountentPanel = this.node.getComponent(cc.ScrollView).content;
        }
        //this.MaskPanel.width = this.node.width;
        //this.MaskPanel.height = this.node.height;

        this.__Scrollview.vertical = this.ViewType == 1 ? false : true;
        this.__Scrollview.horizontal = this.ViewType == 2 ? false : true;
        this.Panel_IndexSize = [this.Panel_Index.width, this.Panel_Index.height];
        //this.node.on(cc.Node.EventType.TOUCH_START, this.OnTouchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.OnTouchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.OnTouchEnd, this);
        this.__Scrollview.node.on('scrolling', this.OnScrollEvent, this);
        this.__Scrollview.inertia = this.IsBrake;
        this.__Scrollview.brake = this.Brake;
    }

    /** 设置上切距离 */
    SetCutTop(cuttop: number) {
        this.CutTop = cuttop;
    }

    /** 设置下切距离 */
    SetCutBottom(cutbottom: number) {
        this.CutBottom = cutbottom;
    }

    /** 设置左切距离 */
    SetCutLeft(cutleft: number) {
        this.CutLeft = cutleft;
    }

    /** 设置右切距离 */
    SetCutRight(cutright: number) {
        this.CutRight = cutright;
    }

    /** 获取文字面板父节点 */
    GetLabelContent() {
        if (this.IsLabelPanel) {
            return this.LabelContent;
        }
        else {
            return null;
        }
    }

    private ItemMsgList = [];

    /** 仅仅清空关键数据，不会删除已经创建好的子面板预制 */
    ClearScrollViewMsg() {
        this._IsLoad = false;
        this.Panel_IndexSize = [];
        this.PanelController = null;
        this.PanelIndexPositionList = [[]];
        this.PanelList = [];
        this.PanelList_L = [];
    }

    GetIsLoad() {
        return this._IsLoad;
    }

    /**
     * 仅仅刷新面板数据
     * 注意：不会将面板重新跳转至第一个面板
     */
    OnlyRefrushPanel() {
        if (this._IsLoad == false) {
            this.OnStartPanel();
            return;
        }
        this.OnTouchStart();
        this.ResetPanelSize();
        this.ResetPanel();
        this.SetData();
        cc.tween(this.node)
            .delay(0.017)
            .call(() => {
                this.OnScrollEvent();
            })
            .start();
    }

    /** 重置当前面板数量 */
    ResetPanel() {
        let PanelArr = this.CountentPanel.children;
        let _index = 0;
        for (let index = 0; index < PanelArr.length; index++) {
            if (index >= this.ItemMsgList.length) {
                PanelArr[index].active = false;
                PanelArr[index].getComponent(ItemPanelController).Clear();
            }
            else {
                if (index == 0) {
                    _index = PanelArr[index].getComponent(ItemPanelController)._INDEX;
                }
                else {
                    PanelArr[index].getComponent(ItemPanelController)._INDEX = _index;
                }
                _index++;
                PanelArr[index].active = true;
            }
        }


        //========================= 如果添加文字面板 =========================
        if (this.IsLabelPanel) {
            for (let index = 0; index < this.LabelContent.length; index++) {
                let LabelPanelArr = this.LabelContent[index].children;
                for (let i = 0; i < PanelArr.length; i++) {
                    if (i >= this.ItemMsgList.length) {
                        LabelPanelArr[i].active = false;
                    }
                    else {
                        LabelPanelArr[i].active = true;
                    }
                }
            }
        }
        //========================= 如果添加文字面板 =========================
    }

    SetData() {


        if (!this.IsLabelPanel) {
            let PanelArr = this.CountentPanel.children;

            //最后一个坐标
            let Endindex = null;
            let TurnToBottom = false;
            let siblinglist = [];

            for (let index = 0; index < PanelArr.length; index++) {
                if (PanelArr[index].active == false) {
                    continue;
                }


                let con = PanelArr[index].getComponent(ItemPanelController);//当前面板控制器
                let _index = 0;
                let panel = null;
                if (this.ItemMsgList.length > con._INDEX) {
                    _index = con._INDEX;
                    panel = PanelArr[index];

                    if (Endindex == null) {
                        Endindex = _index;
                    }
                    else {
                        Endindex = Endindex < _index ? Endindex : _index;
                    }
                }
                else {

                    if (Endindex == null) {
                        Endindex = this.ItemMsgList.length - 1;
                    }
                    else {
                        Endindex--;
                    }
                    _index = Endindex;
                    TurnToBottom = true;

                    if (Endindex < 0) {
                        PanelArr[index].active = false;
                    }
                    else {
                        panel = PanelArr[index];
                        siblinglist.push(PanelArr[index])
                    }
                }

                if (PanelArr[index].active) {
                    panel.x = (this.ViewType == 1 && this.CountentType == 1) ? this.PanelIndexPositionList[_index][0] :
                        (this.ViewType == 1 && this.CountentType == 2) ? -this.PanelIndexPositionList[_index][0] :
                            this.PanelIndexPositionList[_index][0];

                    panel.y = (this.ViewType == 2 && this.CountentType == 1) ? -this.PanelIndexPositionList[_index][1] : (this.ViewType == 2 && this.CountentType == 2) ? this.PanelIndexPositionList[_index][1] : this.PanelIndexPositionList[_index][1];
                    this.ItemAssignment(panel, this.ItemMsgList[_index], _index);
                }

            }

            for (let index = 0; index < siblinglist.length; index++) {
                siblinglist[index].setSiblingIndex(0);
            }

            if (TurnToBottom) {
                this.TurnToBottom();
            }
        }
        else {
            // ========================= 如果添加文字面板 =========================
            let PanelArr = this.CountentPanel.children;
            let LabelPanelList = this.LabelContent;
            //最后一个坐标
            let Endindex = null;
            let TurnToBottom = false;
            let siblinglist = [];
            let siblinglist_L = [];
            for (let index = 0; index < PanelArr.length; index++) {
                if (PanelArr[index].active == false) {
                    continue;
                }
                let con = PanelArr[index].getComponent(ItemPanelController);//当前面板控制器
                let _index = 0;
                let panel = null;
                let panel_L = [];
                if (this.ItemMsgList.length > con._INDEX) {
                    _index = con._INDEX;
                    panel = PanelArr[index];
                    for (let i = 0; i < LabelPanelList.length; i++) {
                        panel_L.push(LabelPanelList[i].children[index]);
                    }
                    if (Endindex == null) {
                        Endindex = _index;
                    }
                    else {
                        Endindex = Endindex < _index ? Endindex : _index;
                    }
                }
                else {

                    if (Endindex == null) {
                        Endindex = this.ItemMsgList.length - 1;
                    }
                    else {
                        Endindex--;
                    }
                    _index = Endindex;
                    TurnToBottom = true;

                    if (Endindex < 0) {
                        PanelArr[index].active = false;
                        for (let i = 0; i < LabelPanelList.length; i++) {
                            LabelPanelList[i][index].active = false;
                        }
                    }
                    else {
                        panel = PanelArr[index];
                        for (let i = 0; i < LabelPanelList.length; i++) {
                            panel_L.push(LabelPanelList[i].children[index]);
                        }
                        siblinglist.push(panel)
                        siblinglist_L.push(panel_L)
                    }
                }

                if (PanelArr[index].active) {
                    panel.x = (this.ViewType == 1 && this.CountentType == 1) ? this.PanelIndexPositionList[_index][0] :
                        (this.ViewType == 1 && this.CountentType == 2) ? -this.PanelIndexPositionList[_index][0] :
                            this.PanelIndexPositionList[_index][0];

                    panel.y = (this.ViewType == 2 && this.CountentType == 1) ? -this.PanelIndexPositionList[_index][1] : (this.ViewType == 2 && this.CountentType == 2) ? this.PanelIndexPositionList[_index][1] : this.PanelIndexPositionList[_index][1];
                    // for (let i = 0; i < panel_L.length; i++) {
                    //     panel_L[i].x = panel.x;
                    //     panel_L[i].y = panel.y;
                    // }

                    this.ItemAssignment(panel, this.ItemMsgList[_index], _index);
                }

            }

            for (let index = 0; index < siblinglist.length; index++) {
                siblinglist[index].setSiblingIndex(0);
                for (let t = 0; t < siblinglist_L[index].length; t++) {
                    siblinglist_L[index][t].setSiblingIndex(0);
                }
            }

            if (TurnToBottom) {
                this.TurnToBottom();
            }
            // ========================= 如果添加文字面板 =========================
        }

    }

    /** 目标面板定位列表 */
    private PanelIndexPositionList: [number[]] = [[]];
    private PanelList: cc.Node[] = [];
    private PanelList_L: cc.Node[][] = [];

    /** 面板属性设定 */
    private ResetPanelSize() {
        this.PanelIndexPositionList = [[]];
        if (this.CountentPanel == null) {
            this.CountentPanel = this.node.getComponent(cc.ScrollView).content;
        }

        let line = (this.PanelCount % this.Division == 0 ? parseInt((this.PanelCount / this.Division).toString()) : parseInt((this.PanelCount / this.Division + 1).toString()));

        /** 设置背景大小 */
        this.CountentPanel.width = this.ViewType == 1 ? (this.CutLeft + this.CutRight + ((line - 1) * this.Interval_X) + (line * this.Panel_Index.width)) : (this.CutLeft + this.CutRight + (this.Division) * this.Panel_Index.width + (this.Division - 1) * this.Interval_X);
        this.CountentPanel.height = this.ViewType == 2 ? (this.CutTop + this.CutBottom + ((line - 1) * this.Interval_Y) + (line * this.Panel_Index.height)) : (this.CutTop + this.CutBottom + (this.Division) * this.Panel_Index.height + (this.Division - 1) * this.Interval_Y);

        if (this.IsLabelPanel) {
            for (let index = 0; index < this.LabelContent.length; index++) {
                this.LabelContent[index].width = this.CountentPanel.width;
                this.LabelContent[index].height = this.CountentPanel.height;
            }
        }

        /** 定位面板位置定位 */
        if (this.Division == 1) {
            for (let index = 0; index < this.PanelCount; index++) {
                if (index == 0) {
                    this.PanelIndexPositionList[0] = [
                        this.ViewType == 1 ? ((this.CountentType == 1 ? this.CutLeft : this.CutRight) + this.Panel_Index.width / 2) : this.ViewType == 2 ? 0 : 0,
                        this.ViewType == 1 ? 0 : this.ViewType == 2 ? ((this.CountentType == 1 ? this.CutTop : this.CutBottom) + this.Panel_Index.height / 2) : 0,
                    ]
                    this.PanelIndexPositionList[0] = [parseFloat(this.PanelIndexPositionList[0][0].toFixed(0)), parseFloat(this.PanelIndexPositionList[0][1].toFixed(0))]
                }
                else {
                    this.PanelIndexPositionList[index] = [
                        this.ViewType == 1 ? ((this.CountentType == 1 ? this.CutLeft : this.CutRight) + (index) * (this.Panel_Index.width + this.Interval_X) + this.Panel_Index.width / 2) : 0,
                        this.ViewType == 1 ? 0 : ((this.CountentType == 1 ? this.CutTop : this.CutBottom) + (index) * (this.Panel_Index.height + this.Interval_Y) + this.Panel_Index.height / 2)
                    ]
                    this.PanelIndexPositionList[index] = [parseFloat(this.PanelIndexPositionList[index][0].toFixed(0)), parseFloat(this.PanelIndexPositionList[index][1].toFixed(0))]
                }
            }
        }
        else {
            let count = 0;
            for (let i = 1; i <= line; i++) {
                for (let j = 1; j <= this.Division; j++) {
                    let _x = this.ViewType == 1 ?
                        ((this.CountentType == 1 ? this.CutLeft : this.CutRight) + this.Panel_Index.width / 2 + (i - 1) * (this.Interval_X + this.Panel_Index.width)) :
                        (-(this.CountentPanel.width / 2) + (this.CountentType == 1 ? this.CutLeft : this.CutRight) + (this.Panel_Index.width / 2) + (j - 1) * (this.Panel_Index.width + this.Interval_X))
                    let _y = this.ViewType == 1 ?
                        (this.CountentPanel.height / 2 - (this.CountentType == 1 ? this.CutTop : this.CutBottom) - (this.Panel_Index.height / 2) - (j - 1) * (this.Interval_Y + this.Panel_Index.height)) :
                        ((this.CountentType == 1 ? this.CutTop : this.CutBottom) + (this.Panel_Index.height / 2) + (i - 1) * (this.Interval_Y + this.Panel_Index.height))

                    if (i == 1 && j == 1) {
                        this.PanelIndexPositionList[0] = [parseFloat(_x.toFixed(0)), parseFloat(_y.toFixed(0))];
                    }
                    else {
                        this.PanelIndexPositionList.push([parseFloat(_x.toFixed(0)), parseFloat(_y.toFixed(0))]);
                    }
                    count++;
                }
            }
        }
        //console.log(this.PanelIndexPositionList)
        /** 是否选择自动获取最佳面板数量 */
        if (this.IfAutoGetMaxPanel) {
            if (this.Division == 1) {
                this.MaxPanel = this.ViewType == 1 ?
                    ((this.__Scrollview.node.width - this.CutLeft - this.CutRight) / (this.Panel_Index.width + this.Interval_X) + 2) :
                    ((this.__Scrollview.node.height - this.CutTop - this.CutBottom) / (this.Panel_Index.height + this.Interval_Y) + 2);
                this.MaxPanel = parseInt(this.MaxPanel.toString()) + 1;
            }
            else {
                this.MaxPanel = this.ViewType == 1 ?
                    ((this.__Scrollview.node.width - this.CutLeft - this.CutRight) / (this.Panel_Index.width + this.Interval_X) + 2) :
                    ((this.__Scrollview.node.height - this.CutTop - this.CutBottom) / (this.Panel_Index.height + this.Interval_Y) + 2);
                this.MaxPanel = parseInt(this.MaxPanel.toString()) + 1;
                this.MaxPanel = this.Division * this.MaxPanel;
            }
        }

    }

    /** 仅仅countent面板回到位置 */
    JustCountentPanelPositionReset() {
        /** countent面板归零 */
        this.CountentPanel.anchorX = (this.ViewType == 1 && this.CountentType == 1) ? 0 : (this.ViewType == 1 && this.CountentType == 2) ? 1 : 0.5;
        this.CountentPanel.anchorY = (this.ViewType == 2 && this.CountentType == 1) ? 1 : (this.ViewType == 2 && this.CountentType == 2) ? 0 : 0.5;
        this.CountentPanel.x = 0;
        this.CountentPanel.y = 0;

        if (this.ViewType == 1) {
            if (this.CountentType == 1) {
                this.CountentPanel.x = - this.MaskPanel.width / 2;
            }
            else {
                this.CountentPanel.x = this.MaskPanel.width / 2;
            }
        }
        else {
            if (this.CountentType == 1) {
                this.CountentPanel.y = this.MaskPanel.height / 2;
            }
            else {
                this.CountentPanel.y = - this.MaskPanel.height / 2;
            }
        }

        // ========================= 如果添加文字面板 =========================
        if (this.IsLabelPanel) {
            for (let index = 0; index < this.LabelContent.length; index++) {
                this.LabelContent[index].anchorX = this.CountentPanel.anchorX;
                this.LabelContent[index].anchorY = this.CountentPanel.anchorY;
                this.LabelContent[index].x = 0;
                this.LabelContent[index].y = 0;

                if (this.ViewType == 1) {
                    this.LabelContent[index].x = this.CountentPanel.x;
                }
                else {
                    this.LabelContent[index].y = this.CountentPanel.y;
                }
            }

        }
        // ========================= 如果添加文字面板 =========================

        /** 如果右widget定位在这里可以出触发一下widget的update() */
        /** 有问题，暂时不开 */
        //this.CountentPanel.getComponent(cc.Widget).updateAlignment();

    }

    /** 
     * 初次进入，创建面板
     */
    private AddPanel() {

        /** 设置基本面板 */
        if (this._PanelLoad == false) {
            for (let index = 0; index < this.MaxPanel; index++) {
                if (this.IsLabelPanel) {
                    // ========================= 如果添加文字面板 =========================
                    let _panel = cc.instantiate(this.Panel_Index);
                    let _panel_L = [];
                    for (let i = 0; i < this.LabelPanel_Index.length; i++) {
                        _panel_L.push(cc.instantiate(this.LabelPanel_Index[i]))
                    };

                    let _con = _panel.getComponent(this.PanelController);
                    if (_con == null) {
                        _panel.addComponent(this.PanelController);
                    }
                    _panel.parent = this.CountentPanel;
                    _panel.name = index.toString();
                    for (let i = 0; i < _panel_L.length; i++) {
                        _panel_L[i].parent = this.LabelContent[i];
                        _panel_L[i].name = index.toString();
                    }


                    let _pCon = _panel.getComponent(ItemPanelController);
                    _pCon._ScrollViewMgr = this;
                    _pCon.onStart();

                    if (index >= this.PanelCount) {
                        _pCon._INDEX = index;
                        _panel.active = false;
                        _pCon.Clear();
                        for (let i = 0; i < _panel_L.length; i++) {
                            _panel_L[i].active = false;
                        }

                    }
                    else {
                        _panel.active = true;
                        _panel.x = (this.ViewType == 1 && this.CountentType == 1) ? this.PanelIndexPositionList[index][0] : (this.ViewType == 1 && this.CountentType == 2) ? -this.PanelIndexPositionList[index][0] : this.PanelIndexPositionList[index][0];
                        _panel.y = (this.ViewType == 2 && this.CountentType == 1) ? -this.PanelIndexPositionList[index][1] : (this.ViewType == 2 && this.CountentType == 2) ? this.PanelIndexPositionList[index][1] : this.PanelIndexPositionList[index][1];
                        this.ItemAssignment(_panel, this.ItemMsgList[index], index);


                    }
                    // ========================= 如果添加文字面板 =========================
                }
                else {
                    let _panel = cc.instantiate(this.Panel_Index);
                    let _con = _panel.getComponent(this.PanelController);
                    if (_con == null) {
                        _panel.addComponent(this.PanelController);
                    }
                    _panel.parent = this.CountentPanel;
                    _panel.name = index.toString();
                    let _pCon = _panel.getComponent(ItemPanelController);
                    _pCon._ScrollViewMgr = this;
                    _pCon.onStart();
                    if (index >= this.PanelCount) {
                        _pCon._INDEX = index;
                        _panel.active = false;
                        _pCon.Clear();
                    }
                    else {
                        _panel.active = true;
                        _panel.x = (this.ViewType == 1 && this.CountentType == 1) ? this.PanelIndexPositionList[index][0] : (this.ViewType == 1 && this.CountentType == 2) ? -this.PanelIndexPositionList[index][0] : this.PanelIndexPositionList[index][0];
                        _panel.y = (this.ViewType == 2 && this.CountentType == 1) ? -this.PanelIndexPositionList[index][1] : (this.ViewType == 2 && this.CountentType == 2) ? this.PanelIndexPositionList[index][1] : this.PanelIndexPositionList[index][1];
                        this.ItemAssignment(_panel, this.ItemMsgList[index], index);
                    }
                }



            }
            this._PanelLoad = true;
        }
        else {
            let PanelArr = this.CountentPanel.children;
            for (let index = 0; index < PanelArr.length; index++) {
                let con = PanelArr[index].getComponent(ItemPanelController);
                con._INDEX = index;

                if (index >= this.PanelCount) {
                    con._INDEX = index;
                    PanelArr[index].active = false;
                    con.Clear();
                }
                else {
                    PanelArr[index].active = true;
                    PanelArr[index].x = (this.ViewType == 1 && this.CountentType == 1) ? this.PanelIndexPositionList[index][0] : (this.ViewType == 1 && this.CountentType == 2) ? -this.PanelIndexPositionList[index][0] : this.PanelIndexPositionList[index][0];
                    PanelArr[index].y = (this.ViewType == 2 && this.CountentType == 1) ? -this.PanelIndexPositionList[index][1] : (this.ViewType == 2 && this.CountentType == 2) ? this.PanelIndexPositionList[index][1] : this.PanelIndexPositionList[index][1];
                    this.ItemAssignment(PanelArr[index], this.ItemMsgList[index], index);
                }
            }

            // ========================= 如果添加文字面板 =========================
            if (this.IsLabelPanel) {
                let LabelPanelArr = [];
                for (let i = 0; i < this.LabelContent.length; i++) {
                    LabelPanelArr.push(this.LabelContent[i].children)
                }
                for (let index = 0; index < LabelPanelArr.length; index++) {
                    if (index >= this.PanelCount) {
                        for (let i = 0; i < LabelPanelArr.length; i++) {
                            LabelPanelArr[i][index].active = false;
                        }
                    }
                    else {
                        for (let i = 0; i < LabelPanelArr.length; i++) {
                            LabelPanelArr[i][index].active = true;
                            LabelPanelArr[i][index].x = (this.ViewType == 1 && this.CountentType == 1) ? this.PanelIndexPositionList[index][0] : (this.ViewType == 1 && this.CountentType == 2) ? -this.PanelIndexPositionList[index][0] : this.PanelIndexPositionList[index][0];
                            LabelPanelArr[i][index].y = (this.ViewType == 2 && this.CountentType == 1) ? -this.PanelIndexPositionList[index][1] : (this.ViewType == 2 && this.CountentType == 2) ? this.PanelIndexPositionList[index][1] : this.PanelIndexPositionList[index][1];

                        }
                    }
                }
            }
            // ========================= 如果添加文字面板 =========================
        }

    }

    private _CountentPanelIndex = {
        x: 0,
        y: 0
    };
    /** 滚动类型 0:第一次 1向下滚动 2向上 3左 4右 5开始 */
    private _ScrollType = 0;
    /** 滚动事件 */
    private OnScrollEvent(Type = 1) {

        let SetNowContent = () => {
            //如果失败了，那么记录坐标，成功了再次刷新，以防漏刷
            this._CountentPanelIndex = {
                x: this.CountentPanel.x,
                y: this.CountentPanel.y,
            };
        }

        // ========================= 如果添加文字面板 =========================
        if (this.IsLabelPanel) {
            for (let index = 0; index < this.LabelContent.length; index++) {
                this.LabelContent[index].x = this.CountentPanel.x;
                this.LabelContent[index].y = this.CountentPanel.y;
            }

        }
        // ========================= 如果添加文字面板 =========================

        if (Type == 1) {
            this._ScrollType = this._ScrollType;
        }
        else {


            this.PanelList = this.CountentPanel.children;
            if (this._ScrollType == 0) {
                this._CountentPanelIndex = {
                    x: this.CountentPanel.x,
                    y: this.CountentPanel.y
                }
                this._ScrollType = 5;
                return
            }

            let _x = this.CountentPanel.x;
            let _y = this.CountentPanel.y;
            //console.log(this._CountentPanelIndex.x, _x)

            if (this.ViewType == ViewType.横屏) {
                if (_x - this._CountentPanelIndex.x < 0) {
                    this._ScrollType = 3;
                }
                else {
                    this._ScrollType = 4;
                }
            }
            else {
                if (_y - this._CountentPanelIndex.y < 0) {
                    this._ScrollType = 1;
                }
                else {
                    this._ScrollType = 2;
                }
            }
            //console.log(this._ScrollType)
        }

        if (!this._ScrollType) {
            return;
        }

        if (this.PanelList.length == 0) {
            return;
        }

        for (let count = 0; count < this.Division; count++) {
            let _panel1: cc.Node = this.PanelList[0];
            let _panel2: cc.Node = this.PanelList[this.PanelList.length - 1];
            let _panel3: cc.Node = null;
            switch (this._ScrollType) {
                case 1:
                    {
                        if (this.TurnPosition(_panel1).y - this.TurnPosition(_panel2).y > 0) {
                            _panel3 = _panel2;
                        }
                        else {
                            _panel3 = _panel1;
                        }
                    }
                    break;
                case 2:
                    {
                        if (this.TurnPosition(_panel1).y - this.TurnPosition(_panel2).y > 0) {
                            _panel3 = _panel1;
                        }
                        else {
                            _panel3 = _panel2;
                        }
                    }
                    break;
                case 3:
                    {
                        if (this.TurnPosition(_panel1).x - this.TurnPosition(_panel2).x > 0) {
                            _panel3 = _panel2;
                        }
                        else {
                            _panel3 = _panel1;
                        }
                    }
                    break;
                case 4:
                    {
                        if (this.TurnPosition(_panel1).x - this.TurnPosition(_panel2).x > 0) {
                            _panel3 = _panel1;
                        }
                        else {
                            _panel3 = _panel2;
                        }
                    }
                    break;
                default:
                    {
                        console.error('scrollviewMgr 警告 ScrollType 查询失败')
                    }
                    break;
            }
            let cut_updown = (this.MaskPanel.height / 2 + this.Panel_Index.height / 2 + (20))
            let cut_leftright = (this.MaskPanel.width / 2 + this.Panel_Index.width / 2 + (20))
            if (this._ScrollType == 1) {
                if (this.TurnPosition(_panel3).y < -cut_updown) {
                    if (this.CountentType == 1) {
                        let _panel = _panel3;
                        let position = [Math.abs(_panel.x), Math.abs(_panel.y)];
                        if (this.Division > 1) {
                            position = [_panel.x, Math.abs(_panel.y)];
                        }
                        let index = this.GetIndexOfArray(position, this.PanelIndexPositionList)
                        let _index = index - this.MaxPanel
                        if (index == -1 || _index < 0) {
                            SetNowContent();
                            return;
                        }
                        else {
                            let position = {
                                x: this.PanelIndexPositionList[_index][0],
                                y: this.PanelIndexPositionList[_index][1]
                            }
                            _panel.x = position.x;
                            _panel.y = -position.y;
                            this.ItemAssignment(_panel, this.ItemMsgList[_index], _index);
                        }
                        _panel.setSiblingIndex(0);
                        this.OnScrollEvent(1);
                    }
                    else {
                        let _panel = _panel3;
                        let position = [Math.abs(_panel.x), Math.abs(_panel.y)];
                        if (this.Division > 1) {
                            position = [_panel.x, _panel.y];
                        }
                        let index = this.GetIndexOfArray(position, this.PanelIndexPositionList);
                        let _index = index + this.MaxPanel
                        if (index == -1 || this.PanelCount - 1 < _index) {
                            SetNowContent();
                            return;
                        }
                        else {
                            let position = {
                                x: this.PanelIndexPositionList[_index][0],
                                y: this.PanelIndexPositionList[_index][1]
                            }
                            _panel.x = position.x;
                            _panel.y = position.y;
                            this.ItemAssignment(_panel, this.ItemMsgList[_index], _index);
                            this.OnScrollEvent(1);
                        }


                        _panel.setSiblingIndex(this.MaxPanel + 1);
                    }
                }
            }
            else if (this._ScrollType == 2) {
                if (this.TurnPosition(_panel3).y > cut_updown) {
                    if (this.CountentType == CountentType["横屏：左到右；竖屏：上到下"]) {

                        let _panel = _panel3;
                        let position = [Math.abs(_panel.x), Math.abs(_panel.y)];
                        if (this.Division > 1) {
                            position = [_panel.x, Math.abs(_panel.y)];
                        }
                        let index = this.GetIndexOfArray(position, this.PanelIndexPositionList)
                        let _index = index + this.MaxPanel
                        if (index == -1 || this.PanelCount - 1 < _index) {
                            SetNowContent();
                            return;
                        }
                        else {
                            let position = {
                                x: this.PanelIndexPositionList[_index][0],
                                y: this.PanelIndexPositionList[_index][1]
                            }
                            _panel.x = position.x;
                            _panel.y = -position.y;
                            this.ItemAssignment(_panel, this.ItemMsgList[_index], _index);
                        }
                        _panel.setSiblingIndex(this.MaxPanel + 1);
                        this.OnScrollEvent(1);


                    }
                    else {
                        let _panel = _panel3;
                        let position = [Math.abs(_panel.x), Math.abs(_panel.y)];
                        if (this.Division > 1) {
                            position = [(_panel.x), _panel.y];
                        }
                        let index = this.GetIndexOfArray(position, this.PanelIndexPositionList);
                        let _index = index - this.MaxPanel
                        if (index == -1 || _index < 0) {
                            SetNowContent();
                            return;
                        }
                        else {
                            let position = {
                                x: this.PanelIndexPositionList[_index][0],
                                y: this.PanelIndexPositionList[_index][1]
                            }
                            _panel.x = position.x;
                            _panel.y = position.y;
                            this.ItemAssignment(_panel, this.ItemMsgList[_index], _index);
                        }
                        _panel.setSiblingIndex(0);
                        this.OnScrollEvent(1);
                    }
                };
            }
            else if (this._ScrollType == 3) {
                if (this.TurnPosition(_panel3).x < -cut_leftright) {
                    if (this.CountentType == 1) {
                        let _panel = _panel3;
                        let position = [Math.abs(_panel.x), Math.abs(_panel.y)];
                        if (this.Division > 1) {
                            position = [_panel.x, _panel.y];
                        }
                        let index = this.GetIndexOfArray(position, this.PanelIndexPositionList)
                        let _index = index + this.MaxPanel
                        if (index == -1 || _index > this.PanelCount - 1) {
                            SetNowContent();
                            return;
                        }
                        else {
                            let position = {
                                x: this.PanelIndexPositionList[_index][0],
                                y: this.PanelIndexPositionList[_index][1]
                            }
                            _panel.x = position.x;
                            _panel.y = position.y;
                            this.ItemAssignment(_panel, this.ItemMsgList[_index], _index);
                        }
                        _panel.setSiblingIndex(this.MaxPanel);
                        this.OnScrollEvent(1);

                    }
                    else {
                        let _panel = _panel3;
                        let position = [Math.abs(_panel.x), Math.abs(_panel.y)];
                        if (this.Division > 1) {
                            position = [Math.abs(_panel.x), _panel.y];
                        }
                        let index = this.GetIndexOfArray(position, this.PanelIndexPositionList);
                        let _index = index - this.MaxPanel
                        if (index == -1 || _index < 0) {
                            SetNowContent();
                            return;
                        }
                        else {
                            let position = {
                                x: this.PanelIndexPositionList[_index][0],
                                y: this.PanelIndexPositionList[_index][1]
                            }
                            _panel.x = -position.x;
                            _panel.y = position.y;
                            this.ItemAssignment(_panel, this.ItemMsgList[_index], _index);
                        }
                        _panel.setSiblingIndex(0);
                        this.OnScrollEvent(1);
                    }
                }
            }
            else if (this._ScrollType == 4) {
                if (this.TurnPosition(_panel3).x > cut_leftright) {
                    if (this.CountentType == 1) {
                        let _panel = _panel3;
                        let position = [Math.abs(_panel.x), Math.abs(_panel.y)];
                        if (this.Division > 1) {
                            position = [_panel.x, _panel.y];
                        }
                        let index = this.GetIndexOfArray(position, this.PanelIndexPositionList)
                        let _index = index - this.MaxPanel
                        if (index == -1 || _index < 0) {
                            SetNowContent();
                            return;
                        }
                        else {
                            let position = {
                                x: this.PanelIndexPositionList[_index][0],
                                y: this.PanelIndexPositionList[_index][1]
                            }
                            _panel.x = position.x;
                            _panel.y = position.y;
                            this.ItemAssignment(_panel, this.ItemMsgList[_index], _index);
                        }
                        _panel.setSiblingIndex(0);
                        this.OnScrollEvent(1);
                    }
                    else {
                        let _panel = _panel3;
                        let position = [Math.abs(_panel.x), Math.abs(_panel.y)];
                        if (this.Division > 1) {
                            position = [Math.abs(_panel.x), _panel.y];
                        }
                        let index = this.GetIndexOfArray(position, this.PanelIndexPositionList);
                        let _index = index + this.MaxPanel
                        if (index == -1 || _index > this.PanelCount - 1) {
                            //如果失败了，那么记录坐标，成功了再次刷新，以防漏刷
                            SetNowContent();
                            return;
                        }
                        else {
                            let position = {
                                x: this.PanelIndexPositionList[_index][0],
                                y: this.PanelIndexPositionList[_index][1]
                            }
                            _panel.x = -position.x;
                            _panel.y = position.y;
                            this.ItemAssignment(_panel, this.ItemMsgList[_index], _index);
                        }
                        _panel.setSiblingIndex(this.MaxPanel - 1);
                        this.OnScrollEvent(1);
                    }
                };
            }
        }

        SetNowContent();

    }

    /** 面板重新分配 */
    private ItemAssignment(Panel: cc.Node, ItemMsg: any, _INDEX: number) {
        let con = Panel.getComponent(ItemPanelController)
        con.Clear();
        con._INDEX = _INDEX;
        con.ResetPanel(ItemMsg);
        //分配完后再次判断，防止漏刷
        this.OnScrollEvent();
    }

    private GetIndexOfArray(arr1: number[], arr2: [number[]]) {

        let _index = -1;

        for (let index = 0; index < arr2.length; index++) {
            if (arr1.toString() == arr2[index].toString()) {
                return index;
            }
        }

        return _index;
    }

    private TurnPosition(node1: cc.Node) {
        let obj = {
            x: node1.x + node1.parent.x,
            y: node1.y + node1.parent.y
        }
        return obj;
    }

    private OnTouchStart() {
        this._CountentPanelIndex = {
            x: this.CountentPanel.x,
            y: this.CountentPanel.y
        }
    }

    private OnTouchEnd() {
        this._CountentPanelIndex = {
            x: 0,
            y: 0
        }
        this._ScrollType = 0;
    }

    //----------------------------------------------------------------
    //代码贡献者： 422925515 吃过多少面包
    //https://forum.cocos.org/t/scrollview/94132/8
    //经检测后发现代码无效，已修改，可使用

    // 目标item的index
    GetTargetIndexOffset(targetIndex) {

        if (this.ViewType == 2) {
            if (this.CountentType == 1) {
                let position = this.PanelIndexPositionList[targetIndex - 1];
                let offset = [];
                offset[0] = position[0];
                offset[1] = position[1] - this.Panel_Index.height / 2;
                return offset;
            }
            else {
                let position = this.PanelIndexPositionList[this.ItemMsgList.length - (targetIndex)];
                let offset = [];
                offset[0] = position[0];
                offset[1] = position[1] - this.Panel_Index.height / 2;
                return offset;
            }
        }
        else if (this.ViewType == 1) {
            if (this.CountentType == 1) {
                let position = this.PanelIndexPositionList[targetIndex - 1];
                let offset = [];
                offset[0] = position[0] - this.Panel_Index.width / 2;
                offset[1] = position[1];
                return offset;
            }
            else {
                let position = this.PanelIndexPositionList[this.ItemMsgList.length - (targetIndex)];
                let offset = [];
                offset[0] = position[0] - this.Panel_Index.width / 2;
                offset[1] = position[1];
                return offset;
            }
        }

    }

    //----------Fuction----------

    //设置属性
    SetScroll(item: any[], controller) {
        this.ItemMsgList = item;
        this.PanelCount = this.ItemMsgList.length;
        this.PanelController = controller;
    }

    /** 
     * 开始加载面板数据
     * 第一次加载面板时调用
     * 之后调用会将面板重置到第一个面板
     */
    OnStartPanel() {
        if (this._IsLoad == true) {
            this.OnlyRefrushPanel();
            return;
        }
        else {
            this._IsLoad = true;
            this.onStart();
            this.ResetPanelSize();
            this.JustCountentPanelPositionReset();
            this.AddPanel();
        }
    }

    /** 跳转至目标面板 */
    ToIndex(targetIndex) {
        let offset = this.GetTargetIndexOffset(targetIndex)
        this.__Scrollview.scrollToOffset(new cc.Vec2(offset[0], offset[1]), 1);
    }

    //跳转至最高点
    TurnToTop() {
        if (this.ViewType == ViewType.横屏 && this.CountentType == CountentType["横屏：左到右；竖屏：上到下"]) {
            this.__Scrollview.scrollToLeft();
        }
        else if (this.ViewType == ViewType.横屏 && this.CountentType == CountentType["横屏：右到左；竖屏：下到上"]) {
            this.__Scrollview.scrollToRight();
        }
        else if (this.ViewType == ViewType.竖屏 && this.CountentType == CountentType["横屏：左到右；竖屏：上到下"]) {
            this.__Scrollview.scrollToTop();
        }
        else if (this.ViewType == ViewType.竖屏 && this.CountentType == CountentType["横屏：右到左；竖屏：下到上"]) {
            this.__Scrollview.scrollToBottom();
        }
    }

    //跳转至最低点
    TurnToBottom() {
        console.error('TurnToBottom')
        let count = this.ItemMsgList.length;
        let offset = this.GetTargetIndexOffset(count);
        this.__Scrollview.scrollToOffset(new cc.Vec2(offset[0], offset[1]), 1);
    }

    //----------------------------------------------------------------
    //---2021/1/28
    //---快乐的狼王

    /** 通知所有面板 */
    SendAllPanel(res) {
        this.PanelList = this.CountentPanel.children;
        for (let index = 0; index < this.PanelList.length; index++) {
            this.PanelList[index].getComponent(ItemPanelController).OnSendAllPanel(res);
        }
    }

    /** 获取ItemList信息 */
    GetItemList() {
        return this.ItemMsgList;
    }

    /** 更改ItemList信息，信息长度有变化的,数据格式有变化的，需要同步已经显示的面板的，不可使用该方法 */
    SetItemList(arr: any[]) {
        if (arr.length == this.ItemMsgList.length) {
            this.ItemMsgList = arr;
        }
    }

    /** 更改ItemList信息，并刷新面板数据，不会跳转 */
    ChangeItemList(ItemList: any[]) {
        this.ItemMsgList = ItemList;
        this.PanelCount = this.ItemMsgList.length;
        this.OnlyRefrushPanel();
    }

    /** 更改ItemList信息，并刷新面板数据，跳转至最高点 */
    ChangeItemList_TurnTop(ItemList: any[]) {
        this.ItemMsgList = ItemList;
        this.PanelCount = this.ItemMsgList.length;
        this.OnlyRefrushPanel();
        this.TurnToTop();
    }


}